import { START_UPDATE, UPDATE_SUCCESS } from '@/enums/identifier'
import { SendConnectAction } from '../action'
import type { SendConnect } from '../connect'

export class UpdateFileAction extends SendConnectAction {
  constructor(connect: SendConnect) {
    super('updateFile', connect)

    this.addAsyncAction('startUpdate', this.startUpdate_handler, true)
    this.addAsyncAction('updateFile', this.updateFile_handler)
    this.addAsyncAction('updateSuccess', this.updateSuccess_handler)
    this.addAsyncAction('updateFailure', this.updateFailure_handler)

    this.actions.addBranchList([
      ['startUpdate', 'updateFile'],
      ['updateFile', 'updateSuccess'],
      ['updateFile', 'updateFailure']
    ])
  }

  async startUpdate_handler() {
    const p = await this.connect.packetOnceAsync()
    if (p.readBodyAsText() !== START_UPDATE) {
      throw new Error('Invalid packet')
    }
    this.spinner.start('Start file update...')
  }

  async updateFile_handler() {
    const p = await this.connect.packetOnceAsync()

    if (p.readBodyAsText() === UPDATE_SUCCESS) {
      return 'updateSuccess'
    } else {
      return 'updateFailure'
    }
  }

  async updateSuccess_handler() {
    this.spinner.succeed('File update successful')
  }

  async updateFailure_handler() {
    this.logger.error('File update failed')
    this.spinner.fail('File update failed')
  }
}
